﻿using System;
using System.Collections.Generic;
using Loki.Commands;
using Loki.Utils;
using Luna.Model.CRM;
using Luna.UI.Resources;

namespace Luna.UI.CRM
{
    public class ContactListViewModel : LunaViewModel
    {
        public LokiCollection<IContact> Contacts { get; private set; }

        public Action<object> GoogleContactLoader { get; private set; }

        public ContactListViewModel()
        {
            Contacts = CreateTrackedCollection<IContact>();
            Load += ContactListViewModel_Load;
            Init += ContactListViewModel_Init;
            DisplayName = FormNames.CONTACT_LIST;
        }

        private void ContactListViewModel_Init(object P_Sender, EventArgs e)
        {
            Commands.Handle(ApplicationCommands.GOOGLE_REFRESH, GoogleRefresh_Execute);
            GoogleContactLoader = CreateWorker<object, IEnumerable<IContact>>("Google update", GoogleContactLoader_DoWork, GoogleContactLoader_Complete);
        }

        private void ContactListViewModel_Load(object P_Sender, EventArgs e)
        {
        }

        private void GoogleRefresh_Execute(object P_Sender, CommandEventArgs e)
        {
            GoogleContactLoader(null);
        }

        private IEnumerable<IContact> GoogleContactLoader_DoWork(object P_Param)
        {
            return ApplicationModel.CRM.Contacts;
        }

        private void GoogleContactLoader_Complete(IEnumerable<IContact> P_Result)
        {
            Contacts.Clear();
            Contacts.AddRange(P_Result);
        }
    }
}